<?php
// 2020年2月17日22:04:21
namespace app\index\controller\wanlshop;

use app\admin\model\wanlshop\Shopgroup;
use app\common\controller\Wanlshop;
use app\common\library\QueueApi;
use app\common\model\UserGroup;
use app\index\model\wanlshop\ActivityGoodsSku;
use think\Db;
use Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use fast\Tree;
use function fast\e;

/**
 * 产品管理
 * @internal
 */
class Goods extends Wanlshop
{
    protected $noNeedLogin = '';
    protected $noNeedRight = '*';
    protected $searchFields = 'title';
    
    /**
     * Goods模型对象
     * @var \app\index\model\wanlshop\Goods
     */
    protected $model = null;
    
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\index\model\wanlshop\Goods;
        $groupList = UserGroup::where(['status' => 'normal'])->select();
        $shopGroupList = Shopgroup::where(['status' => 'normal'])->select();
        // 类目
        $tree = Tree::instance();
		// 1.0.2升级 过滤隐藏
        $tree->init(model('app\index\model\wanlshop\Category')->where(['type' => 'goods', 'isnav' => 1])->field('id,pid,name')->order('weigh asc,id asc')->select());
        $this->assignconfig('channelList', $tree->getTreeArray(0));
        $this->assignconfig('groupList', $groupList);
        $this->assignconfig('shopGroupList', $shopGroupList);
        $this->view->assign('groupList', $groupList);
        $this->view->assign('shopGroupList', $shopGroupList);
        $this->view->assign("flagList", $this->model->getFlagList());
        $this->view->assign("stockList", $this->model->getStockList());
        $this->view->assign("specsList", $this->model->getSpecsList());
        $this->view->assign("distributionList", $this->model->getDistributionList());
        $this->view->assign("activityList", $this->model->getActivityList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("hotList", $this->model->gethotList());
        $this->view->assign("pricingList", $this->model->getPricingList());
    }
    
    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with(['category','shopsort','brand','sku'=>function($query){
                    $query->where(['state' => '0']);
                }])
                ->where($where)
                ->order($sort, $order)
                ->count();
    
            $list = $this->model
                ->with(['category','shopsort','brand','sku'=>function($query){
                    $query->where(['state' => '0']);
                }])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

           // dump($this->model->getLastSql());
            foreach ($list as $row) {
                $row->getRelation('category')->visible(['name']);
                $row->getRelation('shopsort')->visible(['name']);
                $row->getRelation('brand')->visible(['name']);
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);
    
            return json($result);
        }
        return $this->view->fetch();
    }
    
    /**
     * 选择链接
     */
    public function select()
    {
        if ($this->request->isAjax()) {
            if($this->request->post('type') == 'activity'){
                $goods_ids = $this->request->post('goods_ids/a');
                $list = $this->model
                    ->with(['sku'])
                    ->where([
                        'shop_id' => $this->shop->id,
                        'id' => ['in',$goods_ids]
                    ])
                    ->field('id,title,image')
                    ->select();
                $this->success('','',$list);
            }else{
                return $this->index();
            }

        }
        return $this->view->fetch();
    }
    
    /**
     * 仓库中的宝贝
     */
    public function stock()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with(['category','shopsort','brand','sku'])
                ->where($where)
                ->where([
                    'goods.shop_id' => 0,
                    'goods.parent_id' => 0
                ])
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with(['category','shopsort','brand','sku'])
                ->where($where)
                ->where([
                    'goods.shop_id' => 0,
                    'goods.parent_id' => 0
                ])
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            foreach ($list as $row) {
                $row->getRelation('category')->visible(['name']);
                $row->getRelation('shopsort')->visible(['name']);
                $row->getRelation('brand')->visible(['name']);
                $supply_price = array_column($row->sku,'supply_price');
                $row->supply_price = $supply_price ?  min($supply_price) : 0;
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
    
    /**
     * 添加
     */
	public function add()
	{
		//设置过滤方法
		$this->request->filter(['']);
	    if ($this->request->isPost()) {
	        $params = $this->request->post("row/a");
	        if ($params) {
				// 判断产品属性是否存在
				empty($params['spuItem'])?$this->error(__('请完善：销售信息 - 产品属性')):'';
	            $result = false;
	            Db::startTrans();
	            try {
	                $spudata = isset($params['spu'])?$params['spu']:$this->error(__('请填写销售信息-产品属性'));
	                $spuItem = isset($params['spuItem'])?$params['spuItem']:$this->error(__('请填写销售信息-产品属性-产品规格'));
	                // 获取自增ID
	                $this->model->shop_id = $this->shop->id;
	                $this->model->brand_id = $params['brand_id'];
	                $this->model->category_id = $params['category_id'];
					if(isset($params['attribute'])){
						$this->model->category_attribute = json_encode($params['attribute'], JSON_UNESCAPED_UNICODE);
					}
	                $this->model->title = $params['title'];
	                $this->model->image = $params['image'];
	                $this->model->images = $params['images'];
	                $this->model->description = $params['description'];
	                $this->model->stock = $params['stock'];
	                $this->model->status = $params['status'];
	                $this->model->content = $params['content'];
	                $this->model->shop_category_id = $params['shop_category_id'];
	                $this->model->price = min($params['price']);
	                if($this->model->save()){
	                	$result = true;
	                }
					// 写入SPU
					$spu = [];
					foreach (explode(",", $spudata) as $key => $value) {
					    $spu[] = [
					        'goods_id'	=> $this->model->id,
					        'name'		=> $value,
					        'item'		=> $spuItem[$key]
					    ];
					}
					if(!model('app\index\model\wanlshop\GoodsSpu')->allowField(true)->saveAll($spu)){
						$result == false;
					}
					// 写入SKU
					$sku = [];
					foreach ($params['sku']  as $key => $value) {
					    $sku[] = [
					        'goods_id' 		=> $this->model->id,
					        'difference' 	=> $value,
					        'market_price' 	=> $params['market_price'][$key],
					        'price' 		=> $params['price'][$key],
					        'stock' 		=> $params['stocks'][$key],
					        'weigh' 		=> $params['weigh'][$key]!=''?$params['weigh'][$key] : 0,
					        'sn' 			=> $params['sn'][$key]!=''?$params['sn'][$key] : 'wanl_'.time()
					    ];
					}
					if(!model('app\index\model\wanlshop\GoodsSku')->allowField(true)->saveAll($sku)){
						$result == false;
					}
	                Db::commit();
	            } catch (ValidateException $e) {
	                Db::rollback();
	                $this->error($e->getMessage());
	            } catch (PDOException $e) {
	                Db::rollback();
	                $this->error($e->getMessage());
	            } catch (Exception $e) {
	                Db::rollback();
	                $this->error($e->getMessage());
	            }
	            if ($result !== false) {
	                $this->success();
	            } else {
	                $this->error(__('No rows were inserted'));
	            }
	        }
	        $this->error(__('Parameter %s can not be empty', ''));
	    }
	    $shop_id = $this->shop->id;
		// 判断是否存在品牌
		$row['brand'] = model('app\index\model\wanlshop\Brand')->where(['state' => 1])->count();
		// 判断是否有店铺分类
		$row['shopsort'] = model('app\index\model\wanlshop\ShopSort')->where('shop_id',$shop_id)->count();
		// 判断是否有运费模板
		$row['freight'] = model('app\index\model\wanlshop\ShopFreight')->where('shop_id',$shop_id)->count();
		// 判断是否有寄件人信息
		$row['config'] = model('app\index\model\wanlshop\ShopConfig')->where('shop_id',$shop_id)->find();
		// 打开方式
		$this->assignconfig("isdialog", IS_DIALOG);
		$this->view->assign("row", $row);
		return $this->view->fetch();
	}
    
    /**
     * 编辑
     */
    public function edit($ids = null)
    {
		//设置过滤方法
		$this->request->filter(['']);
        $row = $this->model->get($ids);

        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($row['shop_id'] != $this->shop->id) {
            $this->error(__('You have no permission'));
        }
		// 查询SKU
        $skuItem = model('app\index\model\wanlshop\GoodsSku')
            ->where(['goods_id' => $ids, 'state' => 0])
            ->field('id,difference,difference_en,price,market_price,supply_price,group_price,stock,weigh,sn,sales,state')
            ->order('sort asc')
            ->select();
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $single = $this->request->post('single/a');
            if ($params) {

                $result = false;
                Db::startTrans();
                try {

                    if($params['specs'] == 'single'){
                        // 获取自增ID
                        $data = $params;
                        if($row->allowField(true)->save($data)  !== false){
                            $result = true;
                        }
                        $groupPriceArr = $single['group_price'];
                        $groupPrice = [];
                        foreach ($groupPriceArr as $key => $group){
                            $groupPrice[] = [
                                'group_id' => $key,
                                'price' => $group
                            ];
                        }
                        $skuRow = model('app\index\model\wanlshop\GoodsSku')->where([
                            'goods_id'   => $ids,
                            'difference' => '默认',
                        ])->order('createtime desc')->find();
                        $sku[] = [
                            'id' 		=> $skuRow['id'],
                            'goods_id' 		=> $row['id'],
                            /*'difference' 	=> '默认',
                            'market_price' 	=> $single['market_price'],
                            'supply_price' 	=> $single['supply_price'],*/
                            'group_price' 	=> json_encode($groupPrice),
                            'price' 		=> $single['price'],
                            /*'stock' 		=> $single['stock'],
                            'weigh' 		=> $single['weigh']!=''?$single['weigh'] : 0,
                            'sn' 			=> $single['sn']!=''?$single['sn'] : 'xts_'.time()*/
                        ];
                        // 删除原来数据,重新写入SPU
                        model('app\index\model\wanlshop\GoodsSpu')
                            ->where('goods_id','in',$ids)
                            ->delete();
                        $spu[] = [
                            'goods_id' => $ids,
                            'name' => '规格',
                            'name_en' => 'specifications',
                            'item' => '默认',
                            'item_en' => 'default',
                        ];
                        if(!model('app\index\model\wanlshop\GoodsSpu')->allowField(true)->saveAll($spu)){
                            $result == false;
                        }
                    }
                    else{
                        // 判断产品属性是否存在
                        empty($params['spuItem'])?$this->error(__('请完善：销售信息 - 产品属性')):'';
                        $spudata = isset($params['spu'])?$params['spu']:$this->error(__('请填写销售信息-产品属性'));
                        $spuItem = isset($params['spuItem'])?$params['spuItem']:$this->error(__('请填写销售信息-产品属性-产品规格'));
                        // 写入表单
                        $data = $params;
                        if(isset($data['attribute'])){
                            $data['category_attribute'] = json_encode($data['attribute'], JSON_UNESCAPED_UNICODE);
                        }
                        $data['price'] = min($data['price']);
                        $result = $row->allowField(true)->save($data);
                        // 删除原来数据,重新写入SPU
                        model('app\index\model\wanlshop\GoodsSpu')
                            ->where('goods_id','in',$ids)
                            ->delete();
                        $spu = [];
                        foreach (explode(",", $spudata) as $key => $value) {

                            $value = explode('|',$value);
                            $name = $value[0] ?? '';
                            $name_en = $value[1] ?? $value[0];

                            $item = [];
                            $item_en = [];
                            foreach (explode(',',$spuItem[$key]) as $val){
                                $v = explode('|',$val);
                                $item[] = $v[0] ?? '';
                                $item_en[] = $v[1] ?? $v[0];
                            }
                            $spu[] = [
                                'goods_id' => $ids,
                                'name' => $name,
                                'name_en' => $name_en,
                                'item' => implode(',',$item),
                                'item_en' => implode(',',$item_en),
                            ];
                        }

                        if(!model('app\index\model\wanlshop\GoodsSpu')->allowField(true)->saveAll($spu)){
                            $result == false;
                        }
                        //标记旧版SKU数据
                        $oldsku = [];
                        foreach ($skuItem as $value) {
                            $oldsku[] = [
                                'id' => $value['id'],
                                'state' => 1
                            ];
                        }
                        if(!model('app\index\model\wanlshop\GoodsSku')->allowField(true)->saveAll($oldsku)){
                            $result == false;
                        }
                        // 写入SKU
                        $sku = [];
                        foreach ($params['sku'] as $key => $value) {
                            $difference = [];
                            $difference_en = [];
                            foreach (explode(',',$value) as $val){
                                $v = explode('|',$val);
                                $difference[] = $v[0] ?? '';
                                $difference_en[] = $v[1] ?? $v[0];
                            }
                            $skuRow = model('app\index\model\wanlshop\GoodsSku')->where([
                                'goods_id'   => $ids,
                                'difference' => implode(',',$difference),
                            ])->order('createtime desc')->find();
                            if($skuRow){
                                $sku[] = [
                                    'id'           => $skuRow['id'],
                                    'goods_id'     => $ids,
                                    /*'difference'   => implode(',',$difference),
                                    'difference_en'=> implode(',',$difference_en),
                                    'market_price' => $params['market_price'][$key],*/
                                    'price'        => $params['price'][$key],
                                    /*'supply_price' => $params['supply_price'][$key],*/
                                    'group_price'  => $params['group_price'][$key],
                                    /*'stock'        => $params['stocks'][$key],
                                    'sort'         => $params['sort'][$key],
                                    'weigh'        => $params['weigh'][$key]!=''?$params['weigh'][$key] : 0,
                                    'sn'           => $params['sn'][$key]!=''?$params['sn'][$key] : 'wanl_'.time(),*/
                                    'state'        => 0
                                ];
                            }else{
                                $sku[] = [
                                    'goods_id'      => $ids,
                                    'difference'    => implode(',',$difference),
                                    'difference_en' => implode(',',$difference_en),
                                    'market_price'  => $params['market_price'][$key],
                                    'price'         => $params['price'][$key],
                                    'supply_price'  => $params['supply_price'][$key],
                                    'group_price'   => $params['group_price'][$key],
                                    'stock'         => $params['stocks'][$key],
                                    'sort'          => $params['sort'][$key],
                                    'weigh'         => $params['weigh'][$key]!=''?$params['weigh'][$key] : 0,
                                    'sn'            => $params['sn'][$key]!=''?$params['sn'][$key] : 'wanl_'.time(),

                                ];
                            }

                        }
                    }

                    if(!model('app\index\model\wanlshop\GoodsSku')->allowField(true)->saveAll($sku)){
                        $result == false;
                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $spuData = model('app\index\model\wanlshop\GoodsSpu')->all(['goods_id' => $ids]);
        $suk = [];
        $goodsSku = [];
        foreach ($skuItem as $vo) {
            $difference = $vo['difference'];
            if($vo['difference'] != $vo['difference_en']){
                $differenceArr = [];
                $diffArr = explode(',',$vo['difference']);
                $diffEnArr = explode(',',$vo['difference_en']);
                foreach ($diffArr as $key => $diff){
                    $differenceArr[] = isset($diffEnArr[$key]) ? $diff . '|' . $diffEnArr[$key] : $diff;
                }
                $difference = implode(',',$differenceArr);
            }

            $suk[] = explode(",", $difference);
            $goodsSku = [
                'price' =>$vo['price'],
                'market_price' =>$vo['market_price'],
                'supply_price' =>$vo['supply_price'],
                'stock' =>$vo['stock'],
                'weigh' =>$vo['weigh'],
                'sn' =>$vo['sn'],
                'group_price' => is_array($vo['group_price']) ? $vo['group_price'] : model('app\index\model\wanlshop\GoodsSku')->GroupPrice($vo['group_price'])
            ];
        }
        $spu = [];
        foreach ($spuData as $vo) {

            $spu[] = $vo['name'] == $vo['name_en'] ? $vo['name'] : $vo['name'] .'|'. $vo['name_en'];
        }
        $spuItem = [];
        foreach ($spuData as $vo) {
            $itemArr = explode(",", $vo['item']);
            $itemEnArr = explode(",", $vo['item_en']);
            $item = [] ;
            foreach ($itemArr as $key => $val){
                $item[] = isset($itemEnArr[$key]) ? $val .'|'. $itemEnArr[$key] : $val;
            }
            $spuItem[] = $item;
        }
        $skulist = [];
        foreach ($skuItem as $vo) {
            $difference = $vo['difference'];
            if($vo['difference'] != $vo['difference_en']){
                $differenceArr = [];
                $diffArr = explode(',',$vo['difference']);
                $diffEnArr = explode(',',$vo['difference_en']);
                foreach ($diffArr as $key => $diff){
                    $differenceArr[] = isset($diffEnArr[$key]) ? $diff . '|' . $diffEnArr[$key] : $diff;
                }
                $difference = implode(',',$differenceArr);
            }
            $vo['group_price'] = is_array($vo['group_price']) ? $vo['group_price'] : model('app\index\model\wanlshop\GoodsSku')->GroupPrice($vo['group_price']);
            $skulist[$difference] = $vo;
        }
        $this->assignconfig('spu', $spu);
        $this->assignconfig('spuItem', $spuItem);
        $this->assignconfig('sku', $suk);
        $this->assignconfig('skuItem', $skulist);
        $this->assignconfig('categoryId', $row['category_id']);
        $this->assignconfig('attribute', json_decode($row['category_attribute']));
        $this->view->assign("row", $row);
        $this->assignconfig("row", $row);
        $this->view->assign("goodsSku", $goodsSku);
        $this->assignconfig("goodsSku", $goodsSku);
        $this->view->assign("shop_id", $this->shop->id);
        return $this->view->fetch();
    }


    /**
     * 添加类目属性
     */
    public function attribute()
    {
        if ($this->request->isAjax()) {
            $id = $this->request->request("id");
            $list  = model('app\index\model\wanlshop\Attribute')
                ->where([
                    'category_id' => $id,
                    'switch' => 1
                ])
                ->select();
            $this->success('查询成功', '', $list);
        }
        $this->error(__('Parameter %s can not be empty', ''));
    }
    
    /**
     * 回收站
     */
    public function recyclebin()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->onlyTrashed()
                ->where($where)
                ->order($sort, $order)
                ->count();
    
            $list = $this->model
                ->onlyTrashed()
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
    
            $result = array("total" => $total, "rows" => $list);
    
            return json($result);
        }
        return $this->view->fetch();
    }
    
    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $this->model->where('shop_id', '=', $this->shop->id);
            $list = $this->model->where($pk, 'in', $ids)->select();
    
            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
    
    /**
     * 真实删除
     */
    public function destroy($ids = "")
    {
        $pk = $this->model->getPk();
        $this->model->where('shop_id', '=', $this->shop->id);
        if ($ids) {
            $this->model->where($pk, 'in', $ids);
        }
        $count = 0;
        Db::startTrans();
        try {
            $list = $this->model->onlyTrashed()->select();
            foreach ($list as $k => $v) {
                $count += $v->delete(true);
            }
            Db::commit();
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        } else {
            $this->error(__('No rows were deleted'));
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
    
    /**
     * 还原
     */
    public function restore($ids = "")
    {
        $pk = $this->model->getPk();
        $this->model->where('shop_id', '=', $this->shop->id);
        if ($ids) {
            $this->model->where($pk, 'in', $ids);
        }
        $count = 0;
        Db::startTrans();
        try {
            $list = $this->model->onlyTrashed()->select();
            foreach ($list as $index => $item) {
                $count += $item->restore();
            }
            Db::commit();
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were updated'));
    }
    
    /**
     * 批量更新
     */
    public function multi($ids = "")
    {
        $ids = $ids ? $ids : $this->request->param("ids");
        if ($ids) {
            if ($this->request->has('params')) {
                parse_str($this->request->post("params"), $values);
                // $values = $this->auth->isSuperAdmin() ? $values : array_intersect_key($values, array_flip(is_array($this->multiFields) ? $this->multiFields : explode(',', $this->multiFields)));
                if ($values) {

                    $this->model->where('shop_id', '=', $this->shop->id);
                    $count = 0;
                    Db::startTrans();
                    try {
                        if(isset($values['status']) && $values['status'] == 'normal'){
                            $cateerror = $this->model->where($this->model->getPk(), 'in', $ids)
                                ->where('shop_category_id',0)->select();
                            if($cateerror){
                                 throw new \think\Exception('请先批量设置分类后才可进行上架操作');
                            }
                            $freighterror = $list = model('app\index\model\wanlshop\ShopFreight')
                                ->with(['freightdata'])
                                ->where('shop_id',$this->shop->id)
                                ->select();
                            if(!$freighterror){
                                throw new \think\Exception('请先去店铺管理-运费模板进行开启运费模板');
                            }
                        }
                        $list = $this->model->where($this->model->getPk(), 'in', $ids)->select();
                        foreach ($list as $index => $item) {
                            $count += $item->allowField(true)->isUpdate(true)->save($values);
                        }
                        Db::commit();
                    } catch (PDOException $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    } catch (Exception $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    }
                    if ($count) {
                        $this->success();
                    } else {
                        $this->error(__('No rows were updated'));
                    }
                } else {
                    $this->error(__('You have no permission'));
                }
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    //将市场商品加入自己的仓库
    public function copy()
    {
        if ($this->request->isPost()) {

            set_time_limit(0);
            $search = $this->request->post('search');
            $ids = $this->request->post('ids');
            $filter = $this->request->post('filter');
            $op = $this->request->post('op');
            if(!$ids){
                $this->error('未选中任何行');
            }
            $whereIds = $ids == 'all' ? '1=1' : ['id' => ['in', explode(',', $ids)]];
            $this->request->get(['search' => $search, 'ids' => $ids, 'filter' => $filter, 'op' => $op]);
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->where($whereIds)
                ->where([
                    'shop_id' => 0,
                    'parent_id' => 0
                ])
                ->where($where)
                ->select();
            foreach ($list as $row) {
                $data = [
                    'id' => $row['id'],
                    'shop_id' => $this->shop->id
                ];
                QueueApi::copy($data);
            }
            $this->success('操作成功');
        }
    }

    // 设置动态调价模式
    public function pricing(){
        $mode = $this->request->param('mode');
        $ids = $this->request->param('ids');
        if($this->request->isPost()){
            $params = $this->request->param('row/a');
            $idsArr = explode(',',$ids);
            Db::startTrans();
            try {
                foreach ($idsArr as $goods_id){
                    $goods = model('app\index\model\wanlshop\Goods')->get($goods_id);
                    if(!$goods){
                        continue;
                    }
                    switch ($mode){
                        case 'ratio':
                        case 'fixed':
                        case 'set':
                            if($goods['pricing'] == $params['pricing'] || $mode == 'set'){
                                $pricingBase = [];
                                foreach ($params['base'] as $key => $base){
                                    $pricingBase[] = [
                                        'group_id' => $key,
                                        'base' => $base
                                    ];
                                }
                                //保存商家设置的调价模式
                                $pricingBase = json_encode($pricingBase);
                                $goods->pricing = $params['pricing'];
                                $goods->pricing_base = $pricingBase;
                                $goods->save();
                                //放入更新价格队列
                                QueueApi::pricing(['goods_id'=>$goods_id]);

                            }
                            break;
                        case 'category':
                            $goods->shop_category_id = $params['shop_category_id'];
                            $goods->save();
                            break;
                        case 'freight':
                            $goods->freight_id = $params['freight_id'];
                            $goods->save();
                            break;
                    }

                }

                Db::commit();
            }catch (\think\Exception $e){
                Db::rollback();
                $this->error($e->getMessage());
            }catch (PDOException $e){
                Db::rollback();
                $this->error($e->getMessage());
            }
           $this->success();
        }
        if($mode == 'ratio'){
            $placeholder = '如填入1.2,即(供货价*1.2) 作为';
        }elseif($mode == 'fixed'){
            $placeholder = '如填入2,即(供货价+2) 作为';
        }else{
            $placeholder = '比例调价填入比例,固定调价请填入金额';
        }

        $this->view->assign('mode',$mode);
        $this->view->assign('ids',$ids);
        $this->view->assign('placeholder',$placeholder);
        return $this->view->fetch();

    }

    // 规格
    public function setsku($ids){
        $activity_id = $this->request->param('activity_id');
        $skulist = [];
        if(!$activity_id){
            // 查询SKU
            $skuItem = collection(model('app\index\model\wanlshop\GoodsSku')
                ->where(['goods_id' => $ids, 'state' => 0])
                ->field('id,difference,difference_en,price,market_price,supply_price,group_price,stock,weigh,sn,sales,state')
                ->order('sort asc')
                ->select())->toArray();


            foreach ($skuItem as $vo) {
                $skulist[] = [
                    'id' => $vo['id'],
                    'difference' => $vo['difference'],
                    'stock' => $vo['stock'],
                    'supply_price' => $vo['supply_price'],
                    'activity_stock' => '',
                    'activity_price' => '',
                    'join' => 0,
                ];
            }
            $this->assignconfig('isView', 0);
        }else{
            $skuItem = collection(ActivityGoodsSku::with(['sku'])->where([
                'activity_id' => $activity_id,
                'activity_goods_sku.goods_id' => $ids,
            ])->select())->toArray();
            foreach ($skuItem as $vo){
                $skulist[] = [
                    'id' => $vo['id'],
                    'difference' => $vo['sku']['difference'],
                    'stock' => $vo['sku']['stock'],
                    'supply_price' => $vo['sku']['supply_price'],
                    'activity_stock' => $vo['stock'],
                    'activity_price' => $vo['price'],
                    'join' => 1,
                ];
            }
            $this->assignconfig('isView', 1);
        }
        $this->assignconfig('skuItem', $skulist);

        return $this->view->fetch();
    }
}
